package com.hunter.config;

import com.hunter.pojo.Configuration;
import com.hunter.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @Classname XMLMapperBuilder
 * @Description 解析mapper.xml文件
 * @Date 2021/7/22 22:46
 * @Created by haojie.liao
 */
public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析mapper.xml文件
     * @param inputStream
     */
    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectList = rootElement.selectNodes("//select");
        if (selectList != null && selectList.size() > 0){
            for (Element element : selectList) {
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String paramterType = element.attributeValue("paramterType");
                String textTrim = element.getTextTrim();
                MapperStatement mapperStatement = new MapperStatement();
                mapperStatement.setId(id);
                mapperStatement.setReturnType(resultType);
                mapperStatement.setParamterType(paramterType);
                mapperStatement.setSql(textTrim);
                String key = namespace + "." + id;
                configuration.getMapperStatementMap().put(key,mapperStatement);

            }
        }
    }
}
